package com.hxz.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.commonmark.node.*;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


import com.hxz.entity.Article;
import com.hxz.mapper.ArticleMapper;
import com.hxz.service.ArticleService;
/**
 * 
 * @author hxz
 * @description 前台文章Service实现类
 * @data 2019年12月4日 下午6:40:41
 */
@Service
public class ArticleServiceImpl implements ArticleService {
	@Autowired
	private ArticleMapper articleMapper;
	
	/**
	 * 文章详情
	 */
	@Cacheable(value="findArticleById",key="'detail_'+#id")
	public Map<String, Article> getById(String id) {
		Map<String, Article> map = new LinkedHashMap<String, Article>();
		Article article = new Article();
		article = articleMapper.findOne(id);
		Parser parser = Parser.builder().build();
		Node document = parser.parse(article.getContent());
		HtmlRenderer renderer = HtmlRenderer.builder().build();
		renderer.render(document);  // "<p>This is <em>Sparta</em></p>\n"
		article.setContent(renderer.render(document));
		map.put("article", article);
		return map;
	}

	/**
	 * 查询所有列表
	 * 
	 * @return
	 */
	public List<Article> list() {

		List<Article> articles = articleMapper.findAllArticle();
		return articles;
	}

	/**
	 * 根据种类名称查询文章
	 * 
	 * @param categoryName
	 */
	public List<Article> getArticleByCategoryName(String categoryName) {

		return articleMapper.findAllByCategoryName(categoryName);
	}

	/**
	 * 删除文章
	 * 
	 * @param id
	 */
	public void delete(String id) {
		articleMapper.delete(id);
	}

	/**
	 * 保存博客,获取时间等
	 * 
	 * @param article
	 */
	public void save(Article article) {
		// 创建yyyy....格式的时间
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String time = simpleDateFormat.format(date);
		article.setDate(time);
		articleMapper.save(article);
	}

	/**
	 * 根据标题查找 此处用到redis模糊查询
	 */
	@Cacheable(value = "searchkey")
	public List<Article> search(String key) {
		
		List<Article> articles = articleMapper.findByTitleLike(key);
		return articles;
	}

	/**
	 * hot文章
	 */

	public List<Article> getHotArticleList() {

		return articleMapper.hotarticle();

	}

	/**
	 * 文章首页获取top3
	 */
	public List<Article> getTop3() {

		return articleMapper.getTop3();
	}

}
